package cn.gdcp.broadcast;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements IOnTimeChangeListener{

    private Button btn1;
    private Button btn2;
    TextView time;
    Receiver receiver;
    WeatherAndTraffic weatherAndTraffic;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        time=findViewById(R.id.time);
        IntentFilter filter=new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction("I");
        filter.addAction("U");

        weatherAndTraffic = new WeatherAndTraffic();
        registerReceiver(weatherAndTraffic,filter);
        receiver =new Receiver(MainActivity.this);
        registerReceiver(receiver,filter);
        changTime();

        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver,filter);



        btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent();
                intent1.setAction("I");
                intent1.putExtra("weather", "下雨");
                intent1.putExtra("wendu", 25);
                sendBroadcast(intent1);
            }
        });

        btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent();
                intent1.setAction("U");
                intent1.putExtra("traffic", "堵车");
                intent1.putExtra("time", 20);
                sendBroadcast(intent1);
            }
        });
    }

    protected void onDestroy(){
        unregisterReceiver(receiver);
        unregisterReceiver(weatherAndTraffic);
        super.onDestroy();
    }


    @Override
    public void changTime() {
        Calendar calendar=Calendar.getInstance();
        int Hour=calendar.get(Calendar.HOUR);
        int min=calendar.get(Calendar.MINUTE);
        StringBuffer buffer =new StringBuffer();
        if(Hour<10){
            buffer.append("0");
        }
        buffer.append(Hour+":");
        if(min<10){
            buffer.append("0");

        }
        buffer.append(min);
        time.setText(buffer);
    }
}
